package org.grow.ceto.service;

import org.grow.ceto.dao.PlayerDao;
import org.grow.ceto.entity.GoldCoinExchangeDto;
import org.grow.ceto.entity.Player;
import org.grow.ceto.exception.CetoException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @Author: xwg
 * @CreateDate: 21-8-29
 */

@Service
public class PlayerService {

    @Autowired
    private PlayerDao playerDao;
    @Transactional
    public Boolean goldCoinExchange(GoldCoinExchangeDto dto){
        Player consumer = playerDao.findByPlayerCode(dto.getConsumerCode());
        Player supplier = playerDao.findByPlayerCode(dto.getSupplierCode());
        if (consumer == null || supplier == null ) {
            throw new CetoException("交易双方账号或不存在",CetoException.PLAYEREXC);
        }
        if (supplier.getGoldCoin()<dto.getCoinQuantity()){
            throw new CetoException("无足够余额可转账,余额："+supplier.getGoldCoin(),CetoException.PLAYEREXC);
        }
        supplier.setGoldCoin(supplier.getGoldCoin()-dto.getCoinQuantity());
        playerDao.save(supplier);
//        throw ex
        consumer.setGoldCoin(consumer.getGoldCoin()+dto.getCoinQuantity());
        playerDao.save(consumer);
        return true;
    }
}
